#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2016-06-18 15:57:48
# @Author  : lichao (qingligongzi@163.com)
# @Link    : http://www.qingligongzi.com
# @Version : 0.0.1

# 网易云音乐热门歌单
# 使用selenium动态加载网页

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup
import sys
from time import sleep
import re

reload(sys)
sys.setdefaultencoding("utf-8")

# 添加chromedriver的目录到PATH
chrome_driver_path = "D:/repository/chromedriver_win32/"
sys.path.append(chrome_driver_path)

# 指定chromedriver路径加载Chrome
driver = webdriver.Chrome(chrome_driver_path + "chromedriver")

# Firefox driver is included in the selenium-server-stanalone.jar available in the downloads
# Firefox不需要安装
# driver = webdriver.Firefox()

# 设置浏览器显示位置
driver.set_window_position(0, 0)
# 设置浏览器显示大小
driver.set_window_size(1024,768)

driver.implicitly_wait(3)
driver.get("http://music.163.com/#/discover/playlist/?order=hot&cat=%E5%85%A8%E9%83%A8&limit=35&offset=0")



g_iframe = driver.find_element_by_id("g_iframe")
driver.switch_to.frame(g_iframe)
# print element.tag_name
# print element.parent
# print element.text

element = driver.find_element_by_id("m-disc-pl-c")
# print element
html = element.get_attribute("innerHTML")

soup = BeautifulSoup(html)

li_items = soup.select("ul#m-pl-container > li")
print("当前页共%s个歌单" % len(li_items))
for item in li_items:

    ucover_div = item.select("div.u-cover")
    if ucover_div is not None and len(ucover_div) > 0:
        ucover_div_img = ucover_div[0].select("img")
        if ucover_div_img is not None and len(ucover_div_img) > 0:
            img_url = ucover_div_img[0].attrs["src"]
            print("头像url:\n%s\n" % img_url)

        ucover_div_a = ucover_div[0].a
        if ucover_div_a is not None:
            name = ucover_div_a.attrs["title"]
            print("歌单名称:\n%s\n" % name)
            href = ucover_div_a.attrs["href"]
            pattern = re.compile("id=(\d+)", re.S)
            result = re.search(pattern, href)
            if result is not None:
                p_id = result.group(1)
                print("歌单id:\n%s\n" % p_id)
        ucover_nb = ucover_div[0].select("span.nb")
        if ucover_nb is not None and len(ucover_nb) > 0:
            played_num = ucover_nb[0].string
            if played_num.find('万') > 0:
                print int(played_num.replace('万','0000'))
            print("播放次数:\n%s\n" % played_num)

    # pattern = re.compile(r"/user/home?id=(\d+)")
    # user_a = item.find_all(href=pattern)
    user_a = item.select('p a[href^="/user"]')
    if user_a is not None and len(user_a) > 0:
        _href = user_a[0].attrs["href"]
        _result = re.search(pattern, _href)
        if _result is not None:
            author_id = _result.group(1)
            print("用户id:\n%s\n" % author_id)
        author_name = user_a[0].string
        print("用户昵称:\n%s\n" % author_name)

sleep(2)

next_btn = driver.find_element_by_xpath("//div[@class='u-page']/a[@class='zbtn znxt']")
if next_btn is not None:
    # 对页面进行操作，解决点击下一页按钮时触发到播放面板上
    # selenium.common.exceptions.WebDriverException: 
    # Message: unknown error: Element is not clickable at point (682, 629). Other element would receive the click
    # 第一种方式：通过执行js让滚动条滚到底部
    # 第二种方式：通过ActionChains细粒度去控制页面
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    next_btn.click()

    # 需要切回顶级窗口，不然获取不到iframe
    driver.switch_to_default_content()

    sleep(2)

    # try:
    #     element = WebDriverWait(driver, 100).until(
    #         # driver.execute_script("return document.readyState;") == "complete"
    #         EC.presence_of_element_located((By.ID, "g_iframe"))
    #     )
    # finally:
    #     driver.quit()

    driver.implicitly_wait(10)

    g_iframe = driver.find_element_by_id("g_iframe")
    driver.switch_to.frame(g_iframe)

    element = driver.find_element_by_id("m-disc-pl-c")
    # print element
    html = element.get_attribute("innerHTML")

    # print html
else:
    driver.close()
